<?php
class url {
	/**
	 * Gets current links representation
	 *
	 * @param string $module module
	 * @param string $action action
	 * @param array $params additional parameters
	 * @param bool $xhtml_amp XHTML ampersand style
	 * @return string
	 */
	public static function get($module = false, $action = false, array $params = array(), $xhtml_amp = true) {
		$gconfig = global_config::get_instance();

		switch ($gconfig->links_view) {
			case "rewrite_slash_delim":
				return self::get_rewrite_slash_delim_view($module, $action, $params);
				break;
			case "default":
			default:
				return self::get_default_view($module, $action, $params, self::get_amp($xhtml_amp));
		}
	}

	/**
	 * Gets default links view
	 *
	 * @access private
	 * @param string $module
	 * @param sring $action
	 * @param array $params
	 * @param string $amp
	 * @return string
	 */
	private static function get_default_view($module, $action, $params, $amp) {
		$out = "index.php?";

		if ($module === false || strlen($module) < 1) return $out;
		$out .= "module=".urlencode($module);

		if ($action === false || strlen($action) < 1) return $out;
		$out .= $amp."action=".urlencode($action);

		if (count($params) !== 0) {
			foreach ($params as $key => $value) {
				$out .= $amp.$key."=".urlencode($value);
			}
		}
		return $out;
	}

	/**
	 * Gets default links view
	 *
	 * @access private
	 * @param string $module
	 * @param sring $action
	 * @param array $params
	 * @return string
	 */
	private static function get_rewrite_slash_delim_view($module, $action, $params) {
		$out = "";

		if ($module === false || strlen($module) < 1) return $out;
		$out .= urlencode($module);

		if ($action === false || strlen($action) < 1) return $out;
		$out .= "/".urlencode($action);

		foreach ($params as $key => $value) {
			$out .= "/".urlencode($value);
		}

		return $out;
	}

	/**
	 * Gets ampersand view
	 *
	 * @param bool $xhtml_amp
	 * @return string
	 */
	private static function get_amp($xhtml_amp) {
		return $xhtml_amp ? "&amp;" : "&";
	}

	/**
	 * Parses params received from Smarty function and returns url
	 *
	 * @param array $params (module, action, xthml_amp, ...)
	 * @return string
	 */
	public static function parse_smarty_func(array $params) {
		if (isset($params['module'])) {
			$module = strval($params['module']);
			unset($params['module']);
		} else {
			$module = false;
		}
		if (isset($params['action'])) {
			$action = strval($params['action']);
			unset($params['action']);
		} else {
			$action = false;
		}
		if (isset($params['xhtml_amp']) && is_bool($params['xhtml_amp'])) {
			$xhtml_amp = $params['xhtml_amp'];
			unset($params['xhtml_amp']);
		} else {
			$xhtml_amp = true;
		}

		return self::get($module, $action, $params, $xhtml_amp);
	}
}
?>